var express = require('express');
var router = express.Router();
const mysql = require('../utils/mysql');
const jwt = require('jsonwebtoken');
const { expressjwt } = require('express-jwt')
const jiami = require('../utils/jiami');
const miyaoTwo = '123';
const upload = require('../utils/upload')
// const fs = require('fs');
// //引入multer
// const multer = require('multer');
// //创建磁盘存储对象 （多文件）
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         //先定义一个动态目录
//         const date = new Date();
//         let s = 'public/';
//         s += date.getFullYear() + '/';
//         s += (date.getMonth() + 1) + '/';
//         s += (date.getDate()) + '/';
//         //mkdirSync同步创建 recursive允许一次创建多个目录
//         fs.mkdirSync(s, { recursive: true })
//         cb(null, s)
//     },

//     filename: function (req, file, cb) {
//         //文件名的指定要求文件名越长越好，避免重复 
//         const date = new Date();
//         let s = '';
//         s += date.getFullYear();
//         s += ('0' + (date.getMonth() + 1)).slice(-2);
//         s += ('0' + (date.getHours() + 1)).slice(-2);
//         s += ('0' + (date.getMinutes() + 1)).slice(-2);
//         s += ('0' + (date.getSeconds() + 1)).slice(-2);
//         s += ('00' + (date.getMilliseconds())).slice(-3);
//         const arr = file.originalname.split('.');
//         s += '.' + arr[arr.length - 1];
//         cb(null, s);
//     }
// })

//创建上传存储的实例对象
// const upload = multer({
//     // dest: 'upload/'
//     storage,

// })


//文件上传 single('pic')单




//注册
router.post('/reg', async function (req, res) {

    let { username, password } = req.body;
    if (username.length < 2 || password.length < 2) {
        res.json({
            flag: false,
            msg: '用户名或密码不符合规则'
        })
    } else {
        const [{ count }] = await mysql('select count(*) as count from users where username=?', [username])
        if (count > 0) {
            res.json({
                flag: false,
                msg: '用户已注册',
            })
        } else {
            await mysql('insert into users (username,password,createTime,updateTime) values (?,?,now(),now())', [username, jiami(password)])
            res.json({
                flag: true,
                msg: '注册成功'
            })
        }
    }
})

//登录
router.post('/login', async function (req, res) {
    let { username, password } = req.body;
    console.log(username, password)
    if (username.length < 2 || password.length < 2) {
        res.json({
            flag: false,
            msg: '用户名或密码不正确',
        })
    } else {
        // let result = await mysql('select count(*) as count from users where username=? and password=?', [username, jiami(password)]);
        let result = await mysql('select * from users where username=? and password=?', [username, jiami(password)]);

        console.log(result);
        // result[0].count == 0
        if (result.length > 0) {
            res.json({
                flag: true,
                msg: '登录成功',
                data: {
                    token: jwt.sign({ username: username, id: result[0].id }, miyaoTwo, { expiresIn: 60 * 60 })
                }
            })

        } else {
            res.json({
                flag: false,
                msg: '用户名或密码错误'
            })
        }
    }
})
// *************************************************************************
router.all('*', expressjwt({
    secret: miyaoTwo,//密钥
    algorithms: ['HS256']//jwt加密方法
}))
//获取用户信息 
router.get('/getUserInfo', async function (req, res) {
    //获取用户的详细信息
    //获取当前用户id
    const userid = req.auth.id;//登录时token里的载荷
    //判断userInfo表中有没有对应的记录
    const user = await mysql('select * from userinfo where userid = ?', [userid]);
    if (user.length > 0) {
        res.json({
            flag: true,
            data: user[0]
        })
    } else {
        await mysql('insert into userinfo (createTime,updateTime,userid) values (now(),now(),?)', [userid]);
        res.json({
            flag: true,
            data: {}
        })
    }

})
//更新用户信息
router.post('/updateUserInfo', upload.single('avatar'), async function (req, res) {
    //获取数据
    let { nickname, gender, birthday } = req.body;
    let avatar = '';
    if (req.file) {
        avatar = req.file.destination.slice(6) + req.file.filename;
    }
    let userid = req.auth.id;
    //更新资源库
    const arrField = [];
    const arrValues = [];
    arrField.push('nickname=?');
    arrValues.push(nickname);
    if (gender) {
        arrField.push('gender=?');
        if (gender == 'male') {
            arrValues.push(false);
        } else {
            arrValues.push(true);
        }
    }
    if (birthday) {
        arrField.push('birthday=?');
        arrValues.push(new Date(birthday));
    }
    if (avatar) {
        arrField.push('avatar=?');
        arrValues.push(avatar);
    }
    arrValues.push(userid);
    let sql = 'update userinfo set ';
    sql += arrField.join(',');
    sql += '  where userid=?'
    const result = await mysql(sql, arrValues);
    console.log(result)
    res.json({
        flag: '更新成功',

    })

})
//发表事件
router.post('/addNote', async function (req, res) {
    const userid = req.auth.id;
    const { title, content } = req.body;
    await mysql('insert into notebook (title,content,userid,createTime,updateTime) values (?,?,?,now(),now())', [title, content, userid]);
    res.json({
        flag: true,
        msg: '插入成功'
    })
})
//查找事件
router.get('/getNote', async function (req, res) {
    const userid = req.auth.id;
    let { search_string, page, per_page } = req.query;
    if (!search_string) {
        search_string = '';
    }
    page = Number(page);
    if (Number.isNaN(page)) {
        page = 1;
    }
    //  else {
    //     if (page < 1) {
    //         page = 1;
    //     }
    // }
    per_page = Number(per_page)
    if (Number.isNaN(per_page)) {
        per_page = 1;
    }
    // else {
    //     if (per_page < 10) {
    //         per_page = 1
    //     }
    // }

    // const result = await mysql(
    //     'select * from notebook where title like ? or content like ? and userid = ? ' + ' order by updateTime desc ' + ' limit ?,?',
    //      [
    //     '%' + search_string + '%',
    //   '%' + search_string + '%',
    //   userid, (page - 1) * per_page,
    //     per_page
    //    ]);


    const result = await mysql(
        'select * from notebook where (title like ? or content like ?) and userid = ? ' + ' order by updateTime desc ' + ' limit ?,?',
        ['%' + search_string + '%', '%' + search_string + '%', userid, (page - 1) * per_page, per_page]
    );//(page - 1) * per_page, per_page跳过多少条 获取多少条
    const [{ count: total }] = await mysql('select count(*) as count from notebook ' + 'where (title like ? or content like ?) and userid = ? ', ['%' + search_string + '%', '%' + search_string + '%', userid])
    res.json({
        flag: true,
        data: {
            list: result,
            total: total,
            pageSize: per_page,
        }
    })
})
//获取全部事件
// router.get('/getNote', async function (req, res) {
//     const userid = req.auth.id
//     console.log(userid);
//     const note = await mysql('select * from notebook where userid=?', [userid])
//     console.log(note);
//     if (note.length > 0) {
//         res.json({
//             flag: true,
//             data: note,
//         })
//     }
// })
//删除
router.post('/deleteNote', async function (req, res, next) {
    const { noteid } = req.body;
    await mysql('delete from notebook where id=?', [noteid]);
    res.json({
        flag: true,
        msg: '删除成功'
    })
})
//修改
// router.post('/modifyNote', async function (req, res, next) {
//     const { title, content, id } = req.body
//     await mysql('update notebook set title=?,content=?  where id=?', [title, content, id]);
//     res.json({
//         flag: true,
//         msg: '修改成功'
//     })
// })
module.exports = router;




































// router.post('/upload', upload.any(), function (req, res) {
//     res.json({
//         files: req.files,
//         body: req.body,
//     })
// })
// router.all('/getdata', function (req, res) {
//     res.json(req.auth)
// })